﻿@model PackageListModel
@using Nop.Admin.Models.Logistics
@using Telerik.Web.Mvc
@using Telerik.Web.Mvc.UI
@using System.Web.Mvc.Html

@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;

    //page title
    ViewBag.Title = T("Admin.Logistics.PackageList").Text;
}

@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-configuration.png")" alt="" />
            @T("Admin.Logistics.PackageList")  ---   @T("Admin.Logistics.District").Text: @Model.DistrictName
        </div>
        <div class="options">
            <input type="button" id="print-selected" class="t-button" value="@T("Admin.Logistics.Packages.Print.Selected")" />
        </div>
    </div>

    @Html.HiddenFor(model => model.DistrictId);
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.ShippingStatus):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.ShippingStatus, Model.AvailableShippingStatuses)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.PickUpDistrictId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.PickUpDistrictId, Model.AvailableDistricts)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DeliveryDistrictId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DeliveryDistrictId, Model.AvailableDistricts)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.PickUpZone):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.PickUpZone, Model.AvailableZones)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DeliveryZone):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DeliveryZone, Model.AvailableZones)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.TrackingNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.TrackingNumber)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToPkgNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToPkgNumber)
                <input type="submit" name="go-to-pkg-by-Id" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="button" id="search-packages" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table><br />

    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<LogisticsPackageModel>()
                .Name("package-grid-admin")
                .ClientEvents(events => events
                    .OnDataBinding("onDataBinding")
                    .OnDataBound("onDataBound")
                    .OnComplete("onComplete"))
                .Columns(columns =>
                {
                    columns.Bound(x => x.Id)
                        .Filterable(false)
                        .Template(x => string.Format("<input type='checkbox' name='checkedRecords' value='{0}' class='checkboxGroups'/>", x.Id))
                        .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                        .Centered()
                        .Title("<input id='mastercheckbox' type='checkbox'/>")
                        .Width(50)
                        .HeaderHtmlAttributes(new { style = "text-align:center" });

                    columns.Bound(x => x.Id)
                        .Template(x => Html.ActionLink(x.Id.ToString(), "PackageEdit", "Logistics", new { id = x.Id }, new { }))
                        .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Logistics/PackageEdit/") + "<#= Id #>\"><#= Id #></a>")
                        .Centered();
                    columns.Bound(x => x.ShipmentId)
                        .Template(x => Html.ActionLink(x.ShipmentId.ToString(), "PackageEdit", "Logistics", new { id = x.Id }, new { }))
                        .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Logistics/PackageEdit/") + "<#= Id #>\"><#= ShipmentId #></a>")
                        .Centered();

                    columns.Bound(x => x.OrderId)
                        .Template(x => Html.ActionLink(x.OrderId.ToString(), "PackageEdit", "Logistics", new { id = x.Id }, new { }))
                        .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Logistics/PackageEdit/") + "<#= Id #>\"><#= OrderId #></a>")
                        .Centered();

                    columns.Bound(x => x.TrackingNumber).Title(T("Admin.Orders.Shipments.TrackingNumber").Text).HeaderHtmlAttributes(new { Class = "column-tracking t-header" }); ;
                    columns.Bound(x => x.StatusName).Title(T("Admin.Logistics.Common.Fields.Status").Text).HeaderHtmlAttributes(new { Class = "column-status t-header" }).HtmlAttributes(new { Class = "tablecell-status" });

                    columns.Bound(x => x.PickUpDistrict).Title(T("Admin.Logistics.Common.Fields.PickUpDistrict").Text).HeaderHtmlAttributes(new { Class = "column-pickup t-header" });
                    columns.Bound(x => x.DeliveryDistrict).Title(T("Admin.Logistics.Common.Fields.DeliveryDistrict").Text).HeaderHtmlAttributes(new { Class = "column-delivery t-header" });
                    columns.Bound(x => x.PickUpZone).Title(T("Admin.Logistics.Common.Fields.PZone").Text).HeaderHtmlAttributes(new { Class = "column-pickup t-header" });
                    columns.Bound(x => x.DeliveryZone).Title(T("Admin.Logistics.Common.Fields.DZone").Text).HeaderHtmlAttributes(new { Class = "column-delivery t-header" });
                    columns.Bound(x => x.CreatedOn).Title(T("Admin.Logistics.Common.Fields.CreatedOn").Text)
                        .Template(x => x.CreatedOnStr)
                        .ClientTemplate("<#= CreatedOnStr #>");

                    columns.Bound(x => x.Id)
                        .Template(x => Html.ActionLink(T("Admin.Logistics.PrintPackagingSlip").Text, "PrintPackageWaybillAsPdf", "Logistics", new { id = x.Id }, new { @class = "button-grey download-link", target = "_blank" }))
                        .ClientTemplate("<a class='button-grey download-link' href=\"" + @Url.Content("~/Admin/Logistics/PrintPackageWaybillAsPdf/") + "<#= Id #>\" target=\"_blank\">" + "Print" + "</a>")
                        .Centered()
                        .Title(T("Admin.Logistics.PrintPackagingSlip").Text)
                        .HeaderHtmlAttributes(new { Class = "column-waybill t-header" });
                    columns.Bound(x => x.OrderKindId).Hidden(true);
                })
                .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_PackageList", "Logistics", Model))
                      .EnableCustomBinding(true))
            </td>
        </tr>
    </table>

    <script type="text/javascript">

        var selectedIds = [];

        $(document).ready(function () {

            //search button
            $('#search-packages').click(function () {
                //search
                var grid = $('#package-grid-admin').data('tGrid');
                grid.currentPage = 1; //new search. Set page size to 1
                grid.ajaxRequest();
                //clear selected checkboxes
                $('.checkboxGroups').attr('checked', false).change();
                selectedIds = [];
                return false;
            });

            //"Print selected" button
            $('#print-selected').click(function (e) {
                e.preventDefault();
                //redirect to required URL
                setLocation('@(Url.Action("PrintSelected", "Logistics"))?selectedIds=' + selectedIds.join(","));
                return false;
            });

            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes.
            $('#package-grid-admin input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });

            $('td.tablecell-status').each(function () {
                var content = $(this).text();
                if (content.match(/[0-9]+\/[0-9]+\/[0-9]+/)) {
                    $(this).html('<span class="red">' + content + '</span>');
                }
            });



        });

        function onComplete(e) {
            e.data = null;
        }

        function onDataBinding(e) {
            var searchModel = {
                StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
                EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
                TrackingNumber: $('#@Html.FieldIdFor(model => model.TrackingNumber)').val(),
                ShippingStatus: $('#@Html.FieldIdFor(model => model.ShippingStatus)').val(),
                PickUpDistrictId: $('#@Html.FieldIdFor(model => model.PickUpDistrictId)').val(),
                DeliveryDistrictId: $('#@Html.FieldIdFor(model => model.DeliveryDistrictId)').val(),
                PickUpZone: $('#@Html.FieldIdFor(model => model.PickUpZone)').val(),
                DeliveryZone: $('#@Html.FieldIdFor(model => model.DeliveryZone)').val(),
            };
            e.data = searchModel;
        }

        function onDataBound(e) {
            $('#package-grid-admin input[type=checkbox][id!=mastercheckbox]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();
            changeColorByOrderKind();
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#package-grid-admin input[type=checkbox][id!=mastercheckbox]').length;
            var numChkBoxesChecked = $('#package-grid-admin input[type=checkbox][checked][id!=mastercheckbox]').length;
            $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }

        function changeColorByOrderKind() {
            var trObj = $('#package-grid-admin tbody tr');
            if (trObj.length <= 0) return;
            $.each(trObj, function () {
                var kindId = $(this).find('td:last').text();
                if (kindId == '10') {
                    $(this).css('background-color', '#b6d7a8');
                } else if (kindId == '20') {
                    $(this).css('background-color', '#c9daf8');
                }
            });
        }
    </script>

}